var build_in_channel = $("#build_in_channel"),
    article_channels = $("#article_channels"),
    add_system_channel = $("#add_system_channel"),
    add_custom_channel = $("#add_custom_channel"),
    noChannel = $("#noChannel"),
    channelContainer = $("#channelContainer"),
    itemContainer = $('#itemContainer'),
    channelKey = $('#channelKey'),
    addCmsCnannelTab = $('#addCmsCnannelTab'),
    editChannelTab = $('#editChannelTab'),
    ch_name = $('#ch_name'),
    ch_key = $('#ch_key'),
    edit_channel_btn = $('#edit_channel_btn'),
    cancel_channel_edit_btn = $('#cancel_channel_edit_btn'),
    currentChannel,
    editChannelId,
    addArticleLink = $("#addArticleLink"),
    articles = $("#articles"),
    newArticle = $("#newArticle"),
    loadingArticle = $("#loadingArticle"),
    save_article = $("#save_article"),
    cancel_add_article = $("#cancel_add_article"),
    publishDate = $("#publishDate"),
    editor = $("#editor"),
    articleForm = $("#articleForm"),
    cmsItemTable = $("#cmsItemTable");


/**
 * 获取预置栏目
 */
function loadSystemChannels() {
    $.get("cms/getSystemChannels", function (channels) {
        if (channels) {
            for (var name in channels) {
                build_in_channel.append($("<option></option>").attr("value", name).text(channels[name]));
            }
        }
    });
}
/**
 * 获取现有栏目列表
 */
function getChannels() {
    $.get("cms/getChannels", function (data) {
        if (data.totalSize > 0) {
            var template = $('#channelListTemplate').html();
            Mustache.parse(template);
            var rendered = Mustache.render(template, data);
            noChannel.hide();
            channelContainer.html(rendered);
            $("#channelContainer li").first().trigger("click");
            for (var i = 0; i < data.totalSize; i++) {
                article_channels.append($("<option></option>").attr("value", data.result[i].id).text(data.result[i].name));
            }
        }
    });
}
/**
 * 添加栏目
 * @param {type} channel
 */
function addChannel(channel) {
    $.post("cms/addChannel", channel, function (res) {
        if (res) {
            alert("栏目添加成功");
            location.reload();
        } else {
            alert("栏目添加失败");
        }
    }).fail(function () {
        alert("服务器错误");
    });
}
/**
 * 绑定按钮响应事件
 */
function bindActions() {
    // 系统预置栏目
    add_system_channel.on("click", function () {
        var channel = {
            name: $("#build_in_channel option:selected").text(),
            key: $("#build_in_channel option:selected").val()
        };
        addChannel(channel);
    });
    // 自定义栏目
    add_custom_channel.on("click", function () {
        var channel = {
            key: $("#key").val(),
            name: $("#name").val()
        };
        addChannel(channel);
    });
    // 读取栏目文章列表
    channelContainer.on("click", "li", function () {
        var name = $(this).data("name");
        currentChannel = $(this).data("id");
        channelKey.text(name);
        $("#channelContainer li").removeClass("active");
        $(this).addClass("active");
        loadItems(currentChannel);
    });
    // 编辑栏目按钮
    channelContainer.on("click", "li .edit-channel-link", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var parent = $(this).parents("li");
        editChannelId = parent.data("id");
        ch_key.val(parent.data("key"));
        ch_name.val(parent.data("name"));
        addCmsCnannelTab.hide();
        editChannelTab.show();
    });
    // 删除栏目按钮
    channelContainer.on("click", "li .delete-channel-link", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var url = $(this).data("url");
        if (confirm("确定删除栏目")) {
            $.get(url, function (res) {
                if (res) {
                    alert("栏目已删除");
                    location.reload();
                } else {
                    alert("栏目删除失败");
                }
            }).fail(function () {
                alert("服务器错误");
            });
        }
    });
    // 编辑栏目
    edit_channel_btn.on("click", function (e) {
        $.post("cms/editChannel", {
            id: editChannelId,
            name: ch_name.val(),
            key: ch_key.val(),
        }, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器错误");
        });
    });
    // 取消栏目编辑
    cancel_channel_edit_btn.on("click", function (e) {
        editChannelId = null;
        ch_key.val('');
        ch_name.val('');
        editChannelTab.hide();
        addCmsCnannelTab.show();
    });
    // 添加文章按钮
    addArticleLink.on("click", function () {
        // 清除历史数据
        $("#id").val("");
        $("input[name=parent]").val("");
        $("#title").val("");
        $("#url").val("");
        publishDate.datetimepicker('setDate', new Date());
        $("#article_channels").val(currentChannel);
        editor.code("");
        articles.hide();
        newArticle.show();
    });
    // 编辑文章按钮
    cmsItemTable.on("click", ".edit-item-link", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var id = $(this).data("id");
        $.get("cms/getItem/" + id, function (item) {
            if (item) {
                // 初始化文章信息
                $("#id").val(item.id);
                $("input[name=parent]").val(item.parent);
                $("#title").val(item.title);
                $("#url").val(item.url);
                publishDate.datetimepicker('setDate', new Date(item.publishDate));
                //$("#channelId option[value=" + item.channelId + "]").prop("selected", true);
                $("#article_channels").val(item.channelId);
                editor.code(item.content);
                // 显示编辑面板
                articles.hide();
                newArticle.show();
            } else {
                alert("文章未找到");
            }
        }).fail("服务器错误");
    });
    // 删除文章按钮
    cmsItemTable.on("click", ".delete-item-link", function (e) {
        e.stopPropagation();
        e.preventDefault();
        if (confirm("确认删除文章")) {
            var id = $(this).data("id");
            $.get("cms/deleteItem/" + id, function (res) {
                if (res) {
                    alert("文章已删除");
                    location.reload();
                } else {
                    alert("文章删除失败");
                }
            }).fail("服务器错误");
        }
    });
    // 取消文章编辑
    cancel_add_article.on("click", function () {
        editor.code('');
        newArticle.hide();
        articles.show();
    });
    // 保存文章
    save_article.on("click", function () {
        var data = articleForm.formToJson();
        data.content = editor.code();
        data.publishDate = publishDate.datetimepicker('getDate');
        var channel = $("#article_channels option:selected").text();
        if (channel === '轮播图' && (!data.id || imgUrl)) {
            data.parent = imgUrl;
        }
        $.post("cms/saveItem", data, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器错误");
        });
    });
}

/**
 * 载入文章列表
 * @param {type} id
 */
function loadItems(id) {
    itemContainer.html(loadingArticle.html());
    var template = $('#cmsItemTemplate').html();
    Mustache.parse(template);   // optional, speeds up future uses
    $.get("cms/getItemsByChannelId/" + id, function (data) {
        if (data.totalSize > 0) {
            data.publish = function () {
                return $.format.date(new Date(this.publishDate), "yyyy-MM-dd HH:mm");
            };
            data.createTime = function () {
                return $.format.date(new Date(this.recordTime), "yyyy-MM-dd HH:mm");
            };
            var rendered = Mustache.render(template, data);
            itemContainer.html(rendered);
        } else {
            $("#itemTd").html("尚未添加文章");
        }
    });
}
/**
 *  初始化日历
 */
function initDatePicker() {
    publishDate.datetimepicker({
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        showButtonPanel: false
    });
    // 设置默认日期
    publishDate.datetimepicker('setDate', new Date());

}

var imgUrl;
/**
 * 初始化富文本编辑器
 */
function initEditor() {
    var height = $(window).height() / 2;
    editor.summernote({
        height: height, //set editable area's height
        focus: false, //set focus editable area after Initialize summernote
        lang: 'zh-CN',
        oninit: function () {
        },
        onChange: function (contents, $editable) {
        },
        onImageUpload: function (files, editor, welEditable) {
            /**
             * 图片直接上传到upyun
             */
            var url = 'store/upload';
            var formData = new FormData(), document = files[0];
            formData.append("file", document);
            formData.append("name", document.name + '_' + (new Date()).getTime());
            formData.append("desc", "");
            formData.append("realm", 'CMS_ITEM');
            formData.append("id", $("#id").val());
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    if (res.success) {
                        editor.insertImage(welEditable, res.message);
                        imgUrl = res.message;
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('图片上传失败：服务器错误');
            });
        }
    });
}

// 初始化页面信息
loadSystemChannels();
bindActions();
getChannels();
initDatePicker();
initEditor();